// 云函数入口文件
const cloud = require('wx-server-sdk')


cloud.init()
const db = cloud.database();
var _ = db.command
var $ = db.command.aggregate
const db_orders = db.collection('orders');

// 云函数入口函数
exports.main = async (event, context) => {
  
  try {
    return db_orders.aggregate()
      .match({
        extra_order_date: _.gte(formatDate(new Date()).date_week)
      })
      .lookup({
        from: "user",
        localField: "person",
        foreignField: "name",
        as: "userList"
      })
      .replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$userList', 0]), '$$ROOT'])
      })
      .project({
        userList: 0,
        password: 0
      }).end()
      // .then(res => {
      //   console.log(res)
      //   arr = res

      // })
      // .catch(err => {
      //   console.error(err)
      // })
      // return arr
  } catch (error) {
    console.error(error)
  }

}

const formatDate = date => {
  let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  let year = date.getFullYear();
  let month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
  let day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  let week = show_day[new Date(date).getDay()];
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()


  // return `${year}-${month}-${day}.${week}`;
  return {
    "date": `${year}-${month}-${day}`,
    "time": [hour, minute, second].map(formatNumber).join(':'),
    "week": `${week}`,
    "date_week": `${year}-${month}-${day}.${week}`
  };
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}